class WebSocketClient {
  constructor(options = {}) {
    // 基础配置
    this.url = options.url || ''
    this.reconnectLimit = options.reconnectLimit || 3 // 最大重连次数
    this.reconnectCount = 0 // 当前重连次数
    this.heartbeatInterval = options.heartbeatInterval || 30000 // 心跳间隔
    this.heartbeatTimer = null // 心跳定时器
    
    // 事件处理器
    this.onOpen = null
    this.onMessage = null
    this.onError = null
    this.onClose = null
    
    // 消息队列
    this.messageQueue = []
  }

  // 创建连接
  connect() {
    uni.connectSocket({
      url: this.url,
      success: () => {
        console.log('WebSocket 连接创建成功')
        this._resetReconnect()
        this._setupSocket()
      },
      fail: (err) => {
        console.error('WebSocket 连接失败:', err)
        this._handleReconnect()
      }
    })
  }

  // 初始化 socket 事件监听
  _setupSocket() {
    uni.onSocketOpen(() => {
      console.log('WebSocket 连接已打开')
      this.onOpen?.()
      this._startHeartbeat()
      this._flushMessageQueue()
    })

    uni.onSocketMessage((res) => {
      this.onMessage?.(res.data)
      // 收到消息重置心跳
      this._resetHeartbeat()
    })

    uni.onSocketError((err) => {
      console.error('WebSocket 错误:', err)
      this.onError?.(err)
      this._handleReconnect()
    })

    uni.onSocketClose(() => {
      console.log('WebSocket 连接关闭')
      this.onClose?.()
      this._handleReconnect()
    })
  }

  // 发送消息
  send(data) {
    if (typeof data !== 'string') {
      data = JSON.stringify(data)
    }

    if (this.isConnected()) {
      uni.sendSocketMessage({
        data,
        success: () => {
          console.log('消息发送成功:', data)
        },
        fail: (err) => {
          console.error('消息发送失败:', err)
          this.messageQueue.push(data)
        }
      })
    } else {
      this.messageQueue.push(data)
    }
  }

  // 关闭连接
  close(code = 1000, reason = '正常关闭') {
    this.reconnectCount = this.reconnectLimit
    uni.closeSocket({
      code,
      reason
    })
  }

  // 状态检查
  isConnected() {
    return this.reconnectCount < this.reconnectLimit && 
           this.socketTask?.readyState === WebSocket.OPEN
  }

  // 心跳管理
  _startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      this.send(JSON.stringify({ type: 'ping' }))
    }, this.heartbeatInterval)
  }

  _resetHeartbeat() {
    clearInterval(this.heartbeatTimer)
    this._startHeartbeat()
  }

  // 重连管理
  _handleReconnect() {
    if (this.reconnectCount < this.reconnectLimit) {
      this.reconnectCount++
      console.log(`尝试第 ${this.reconnectCount} 次重连...`)
      setTimeout(() => this.connect(), 2000)
    }
  }

  _resetReconnect() {
    this.reconnectCount = 0
  }

  // 发送队列消息
  _flushMessageQueue() {
    while (this.messageQueue.length > 0) {
      const message = this.messageQueue.shift()
      this.send(message)
    }
  }
}

// 导出
export const wsClient = new WebSocketClient();